const https = require('https');
const fs = require('fs');

const express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto');

const app = express();
const port = 443;

// 中间件解析 JSON 请求体
app.use(bodyParser.json());

app.get('/rest/v1/rpc/health', (req, res) => {
  res.json({ status: 'ok' });
});

app.post('/rest/v1/rpc/generate_verification_token', (req, res) => {
  // 检查请求头
  const apikey = req.headers['apikey'];
  const authorization = req.headers['authorization'];
  // const contentType = req.headers['content-type'];

  if (!apikey || !authorization || 'Bearer ' + apikey !== authorization) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  // 检查请求体
  const { code_hint } = req.body;
  if (!code_hint) {
    return res.status(400).json({ error: 'Bad Request', message: 'Missing code_hint' });
  }

  console.log(`Received code_hint: ${code_hint}`);

  // 生成令牌并返回响应
  const token = crypto.createHash('sha256').update(code_hint).digest('hex').substring(0, 32);  // 使用 SHA256 哈希算法生成令牌
  const expires_in = 30; // 令牌有效期（单位：秒）

  const result = { token, expires_in, code_hint };
  res.json(result);
});

app.post('/rest/v1/rpc/verify_invitation_code', (req, res) => {
  // 检查请求头
  const apikey = req.headers['apikey'];
  const authorization = req.headers['authorization'];
  // const contentType = req.headers['content-type'];

  if (!apikey || !authorization || 'Bearer ' + apikey !== authorization) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  // 检查请求体
  const { client_token, code_input, device_info } = req.body;
  if (!client_token || !code_input || !device_info) {
    return res.status(400).json({ error: 'Bad Request', message: 'Missing required fields' });
  }

  console.log(`Received code_input: ${code_input}`);

  // 验证邀请码
  const result = { message: '验证成功', success: true, code_input };
  res.json(result);
});

app.post('/rest/v1/rpc/check_code_expiration', (req, res) => {
  // 检查请求头
  const apikey = req.headers['apikey'];
  const authorization = req.headers['authorization'];
  // const contentType = req.headers['content-type'];

  if (!apikey || !authorization || 'Bearer ' + apikey !== authorization) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  // 检查请求体
  const { client_token, code_input } = req.body;
  if (!client_token || !code_input) {
    return res.status(400).json({ error: 'Bad Request', message: 'Missing required fields' });
  }

  // 检查邀请码是否过期
  const result = { message: '邀请码未过期', success: true, is_expired: false, code_input };
  res.json(result);
});

// 启动服务器
const options = {
  key: fs.readFileSync('server.key'),
  cert: fs.readFileSync('server.crt')
};

https.createServer(options, app).listen(port, () => {
  console.log(`Server is running on https://localhost:${port}`);
});